package br.edu.ufcg.lsd.wbis.ui.client.ui.management;

import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.services.GeneralService;
import br.edu.ufcg.lsd.wbis.ui.client.ui.AbstractMainPanel;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.AdminPanel;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedout.LoginPanel;
import br.edu.ufcg.lsd.wbis.ui.client.ui.setup.SetupPanel;

import com.google.gwt.user.client.Window;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Viewport;

/**
 * @author Renato Miceli
 */
public class DefaultPanelManager implements PanelManager {

	private Panel currentPanel;

	private final DefaultUserInfoManager manager;

	public DefaultPanelManager() {

		currentPanel = null;
		manager = new DefaultUserInfoManager(new UserInfo());
		manager.start();
		
		GeneralService.Util.getInstance().getRootUserStatus(new RootUserStatusGetterCallback(this));
	}

	private void killCurrentPanel() {
		if (currentPanel != null) {
			currentPanel.destroy();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public Panel getCurrentPanel() {
		return currentPanel;
	}

	/**
	 * {@inheritDoc}
	 */
	public void switchToLoginPanel() {
		killCurrentPanel();
		manager.defaultCancel();
		UserInfo newInfo = new UserInfo();
		newInfo.setLogin(getUserInfo().getLogin());
		setUserInfo(null);
		show(new LoginPanel(this, newInfo));
	}

	/**
	 * {@inheritDoc}
	 */
	public void switchToAdminPanel(UserInfo info) {
		killCurrentPanel();
		setUserInfo(info);
		manager.defaultSchedule();
		show(new AdminPanel(this));
	}

	/**
	 * {@inheritDoc}
	 */
	public void switchToUserPanel() {
		// TODO Auto-generated method stub
	}

	/**
	 * {@inheritDoc}
	 */
	public void switchToSetupPanel() {
		killCurrentPanel();
		manager.defaultCancel();
		show(new SetupPanel(this));
	}

	private void show(AbstractMainPanel panel) {
		currentPanel = panel;
		Window.setTitle(panel.getPageTitle());
		new Viewport(currentPanel);
	}

	public UserInfo getUserInfo() {
		return manager.getInfo();
	}

	public void setUserInfo(UserInfo info) {
		manager.setInfo(info);
	}

	/**
	 * {@inheritDoc}
	 */
	public InfoManager<UserInfo> getInfoManager() {
		return manager;
	}

}
